import styled from 'styled-components';
import React, { CSSProperties, useCallback, useEffect, useState } from 'react';
import { OsType, type } from "@tauri-apps/plugin-os";
import { convertFileSrc } from '@tauri-apps/api/core';
import { Webview } from '@tauri-apps/api/webview';
import { Window, LogicalSize, LogicalPosition, getCurrentWindow } from '@tauri-apps/api/window';
import { WebviewWindow } from '@tauri-apps/api/webviewWindow'

import { Application, applicationGetApplicationByIdentifier, applicationWindowEval, installApplication, appstoreQueryApplicationById } from '../../services';
import { Button } from 'antd';
import { InstalledApplication } from '@/services/local';

export interface ApplicationViewerProps {
    style?: CSSProperties;
    identifier: string;
}

export const ApplicationViewer: React.FC<ApplicationViewerProps> = (props) => {

    const [url, setUrl] = useState<string | null>(null);

    const [application, setApplication] = useState<InstalledApplication | null>(null);

    const [needInstall, setNeedInstall] = useState<boolean>(false);

    useEffect(() => {
        let identifier = props.identifier;
        if (!identifier) {
            setUrl(null);
            return;
        }
        //根据identifier 查询是否安装
        applicationGetApplicationByIdentifier(identifier).then((res) => {
            if (!res || res === null) {
                setNeedInstall(true)
                return;
            }
            //
            setApplication(res);
        });

    }, [props.identifier]);

    useEffect(() => {
        if (!application) return;
        let item = application;
        let pathIdentifier = item.identifier.replace(/\./g, '$');

        let url = `rrg01://${pathIdentifier}.localhost${item.main}`;
        if (type() === 'windows') {
            // url = convertFileSrc(url, "rrg01");
            url = `http://rrg01.${pathIdentifier}.localhost${item.main}`;
        }
        setUrl(url);
    }, [application]);

    if (needInstall) {
        return (
            <InstallPanel identifier={props.identifier} onCompleted={async (result) => {
                //根据identifier 查询是否安装
                applicationGetApplicationByIdentifier(props.identifier).then((res) => {
                    if (!res || res === null) {
                        setNeedInstall(true)
                        return;
                    }
                    setNeedInstall(false)
                    //
                    setApplication(res);
                });
            }}></InstallPanel>
        );
    }

    if (type() === 'windows') {
        //在windows上tauri有一个bug，不之后iframe
        return (
            <EmptyContainer>
                <div>目前在Windows中有一个bug，导致无法在iframe中显示!</div>
                <div><Button danger type={'primary'} onClick={async () => {
                    let windowIdentifier = `browser_0`;
                    let win = await Window.getByLabel(windowIdentifier);
                    if (!win) {
                        win = new WebviewWindow(windowIdentifier, {
                            url: url,
                            width: 1200,
                            height: 800,
                        });
                        win.once('tauri://created', async function () {
                            // window successfully created
                            await applicationWindowEval(windowIdentifier, `window.location.replace('${url}')`);
                            await win.show();
                        });
                        win.once('tauri://error', function (e) {
                            console.log(e);
                        });
                    } else {
                        //
                        await applicationWindowEval(windowIdentifier, `window.location.replace('${url}')`);
                        await win.show();
                    }

                }}>使用新窗口打开</Button></div>
            </EmptyContainer>
        );
    }
    return (
        <Container>
            <IframeNode src={url}></IframeNode>
        </Container>
    );
}


const InstallPanel = (props: { identifier: string, onCompleted: (result: boolean) => Promise<void> }) => {

    const [application, setApplication] = useState<Application | null>(null);

    const [loading, setLoading] = useState<boolean>(false);

    const [installMessages, setInstallMessages] = useState<Array<string>>([]);

    useEffect(() => {
        //
        appstoreQueryApplicationById(props.identifier).then((app) => {
            setApplication(app);
        });
    }, [props.identifier]);

    const processBack = useCallback(async (process) => {
        console.log(process);
        setInstallMessages(installMessages.concat(process.message));
    }, [installMessages]);

    if (loading) {
        return (
            <Container style={{
                display: 'flex',
                flexDirection: 'column',
                justifyContent: 'center',
                alignItems: 'center'
            }}>
                {
                    installMessages && installMessages.map((message, index) => {
                        return (
                            <div key={index}>{message}</div>
                        );
                    })
                }
            </Container>
        );
    }
    return (
        <Container style={{
            display: 'flex',
            flexDirection: 'column',
            justifyContent: 'center',
            alignItems: 'center'
        }}>
            <div>访问的应用还未安装</div>
            <Button type={'link'} onClick={async () => {
                if (application === null) return;
                setLoading(true);
                try {
                    await installApplication(application, processBack);
                } catch (err) {
                    console.log(err);
                    setLoading(false);
                    await props.onCompleted(false);
                    return;
                }
                setLoading(false);
                await props.onCompleted(true);
            }}>点击进行安装</Button>
        </Container>
    );
}

const Container = styled.div`
    height: 100%;
    width: 100%;
`;


const IframeNode = styled.iframe`
    height: 100%;
    width: 100%;
`;

const EmptyContainer = styled.div`
    height: 100%;
    width: 100%;
    display: flex;
    flex-direction: column;
    justify-content: center;
    align-items: center;
    gap: 10px;
`;
